<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/18 0018
 * Time: 上午 11:01
 */
namespace app\common\command;

use app\common\redis\Redis;
use think\Exception;

class Meeting{
    /**
     * 会议提醒
     */
    public static function writequeue(){
        try{
            $nowtime = time();
            $where = [
                'p.startTime' => ['gt',$nowtime]
            ];
            $join = [
                ['__PARTY_MEETING__ p','p.id=a.meetingId'],
                ['__USER__ u','u.id=a.memberId']
            ];
            $field = 'a.memberId,a.meetingId,p.title,p.startTime,p.remind,p.address,u.p_phone';
            $list = db('party_meeting_users')->alias('a')->where($where)->join($join)->field($field)->select();
            if($list){
                $redis = Redis::getRedisConn();
                foreach ($list as $item){
                    // 会议开始时间
                    $startTime = strtotime($item['startTime']);
                    // 提醒时间
                    $remindTime = intval($startTime) - ($item['remind'] * 60);
                    if(date('Y-m-d H:i',$nowtime) == date('Y-m-d H:i',$remindTime)){
                        $data = [];
                        $data['p_phone'] = $item['p_phone'];
                        $data['title'] = $item['title'];
                        $data['startTime'] = $startTime;
                        $data['address'] = $item['address'];
                        if($data['p_phone']){
                            $redis->RPush('zhujian_meeting_mobile_list',json_encode($data));
                        }else{
                            trace('没有手机号','notice');
                        }

                    }
                }
            }

        }catch (Exception $ex){
            trace($ex->getMessage(),'error');
        }
    }
    public static function cron(){
        self::sendsms();
    }

    private static function sendsms(){
        $Redis = Redis::getRedisConn();
        $smsObj = new \app\lib\Sms();
        $meetingdata = $Redis->LRange('zhujian_meeting_mobile_list',0,-1);
        if($meetingdata){
            foreach ($meetingdata as $v){
                $v = json_decode($v,true);
                if(!empty($v)){
                    $message = '';
                    $message .= "会议提醒：\n会议主题：" . $v['title'] . "\n";
                    $message .= '会议开始时间：' . date('Y-m-d H:i',$v['startTime']) . "\n";
                    $message .= '会议地点：' . $v['address']. "\n";
                    $message .= '请务必准时参加 【江陵住建】';

                    $smsRes = $smsObj->sendMsg($v['p_phone'], $message);
                    if (isset($smsRes)) {
                        if ($smsRes['msg'] == 'ok') {
                            $Redis->LRem('zhujian_meeting_mobile_list',json_encode($v),-1);
                        } else {
                            trace($v . ' 短信发送失败','notice');
                        }
                    }
                }

            }
        }
    }
}